package com.honghu.cloud.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.druid.util.Base64;
import com.google.common.collect.Maps;
import com.honghu.cloud.bean.Accessory;
import com.honghu.cloud.bean.FTPServer;
import com.honghu.cloud.code.ResponseCode;
import com.honghu.cloud.common.page.Page;
import com.honghu.cloud.dto.SysConfigDto;
import com.honghu.cloud.feign.SysConfigFeignClient;
import com.honghu.cloud.service.IAccessoryService;
import com.honghu.cloud.service.IFTPServerService;
import com.honghu.cloud.tools.CommUtil;
import com.honghu.cloud.tools.SecurityUserHolder;
import com.honghu.cloud.tools.VideoFrameUtils;
import com.honghu.cloud.tools.ftp.SFtpUtil;
import com.honghu.cloud.utils.DateUtils;
import com.honghu.cloud.utils.EncryptUtil;
import com.honghu.cloud.utils.Exceptions;
import com.jcraft.jsch.ChannelSftp;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

@Slf4j
@RestController
@RequestMapping(value = "/ftp")
// /*@CrossOrigin(origins = "*", maxAge = 3600, methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT })*/
//@CrossOrigin(allowCredentials="true",maxAge = 3600)
public class FtpFileController {

	@Autowired
	private IAccessoryService accessoryService;
	@Autowired
	private IFTPServerService ftpServerService;
	@Autowired
	private SysConfigFeignClient sysConfigFeignClient;
	@Value("${file-upload-path}")
	private String fileUploadPath;
	
	/**
	 * ftp列表(后台管理)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/apiForFeign/list", method = RequestMethod.POST)
	public Map<String,Object> list(@RequestBody Map<String, Object> params) {
		Page<FTPServer> iPageList = ftpServerService.list(params);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("currentPage", iPageList.getCurrentPage());
		resultMap.put("pages", iPageList.getPages());
		resultMap.put("pageSize", iPageList.getPageSize());
		resultMap.put("result", iPageList.getResult());
		resultMap.put("rowCount", iPageList.getRowCount());
		return resultMap;
		
	}
	
	
	
	

	/**
	 * FTP服务器保存
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/ftpserverSave")
	public Map<String, Object> ftpserverSave(@RequestBody FTPServer ftpserver) {
		if (ftpserver.getFtp_amount() == 0) {
			ftpserver.setFtp_amount(100);
		}
		if (ftpserver.getId().equals("")) {
			ftpserver.setAddTime(new Date());
			// 加密Ftp密码
			ftpserver.setFtp_password(EncryptUtil.encrypt(ftpserver.getFtp_password()));
			ftpServerService.save(ftpserver);
		} else {
			FTPServer ftpserverdto = ftpServerService.selectByPrimaryKey(ftpserver.getId());
			// 加密Ftp密码,修改时密码不相等，表示修改了密码，需要重新加密
			if (!StringUtils.equals(ftpserver.getFtp_password(), ftpserverdto.getFtp_password())) {
				ftpserver.setFtp_password(EncryptUtil.encrypt(ftpserver.getFtp_password()));
			}
			ftpServerService.updateById(ftpserver);
		}

		// 新添加的系统服务器若设置为当前使用，将其他系统服务器设置为非当前使用
		if (ftpserver.getFtp_type() == 1 && ftpserver.getFtp_system() == 1) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("ftp_system", 1);
			map.put("hongHu_ftp_id", ftpserver.getId());
			map.put("ftp_type", 1);

			List<FTPServer> objs = this.ftpServerService.queryPageListNotId(map);

			for (FTPServer obj : objs) {
				obj.setFtp_system(0);
				ftpServerService.updateById(obj);
			}
		}

		/*
		 * SysConfigDto config = this.sysConfigFeignClient.getSysConfig();
		 * String uploadFilePath = config.getUploadFilePath(); String path =
		 * request.getSession().getServletContext().getRealPath("/") +
		 * uploadFilePath + File.separator + "cache";
		 * CommUtil.createFolder(path);// 创建缓存目录
		 */
		return ResponseCode.buildSuccessMap(null);
	}
		
		
	
	
	
	/**
	 * 通过字符流上传文件
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/apiForFeign/selectByPrimaryKey", method = RequestMethod.GET)
	public FTPServer selectByPrimaryKey(@RequestParam("id")Long id) {
		FTPServer selectByPrimaryKey = ftpServerService.selectByPrimaryKey(id);
		return selectByPrimaryKey;
	}

	/**保存
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/apiForFeign/save", method = RequestMethod.GET)
	public void save(@RequestBody FTPServer ftpserver) {
		 ftpServerService.save(ftpserver);
	}
	
	/**保存
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/apiForFeign/updateById", method = RequestMethod.GET)
	public void updateById(@RequestBody FTPServer ftpserver) {
		 ftpServerService.updateById(ftpserver);
	}
	
	
	/**
	 * 通过字符流上传文件
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/apiForFeign/uploadByBase64", method = RequestMethod.POST)
	public Boolean uploadByBase64(@RequestBody Map<String, Object> params) {
		ByteArrayInputStream stream = null;
		try {
			String base64 = (String) params.get("base64");
			String folder = (String) params.get("folder");
			String fileName = (String) params.get("fileName");

			byte[] bytes1 = Base64.base64ToByteArray(base64);  
			stream = new ByteArrayInputStream(bytes1); 
			
			// FTP服务器配置
			List<FTPServer> ftpServers = ftpServerService.queryPageList(new HashMap<String, Object>());
			if (ftpServers == null || ftpServers.size() < 1) {
				return false;
			}
						
			// 上传文件到SFTP
			FTPServer ftpServer = ftpServers.get(0);
			ChannelSftp sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), 
					ftpServer.getFtp_username(), EncryptUtil.decrypt(ftpServer.getFtp_password()));
			if (sftp == null) {
				return false;
			}
			Boolean flag = SFtpUtil.upload(sftp, stream, folder, fileName);
			if (!flag) {
				return false;
			}
			return flag;
		} catch (Exception e) {
			log.error("通过字符流上传文件文件："+Exceptions.getStackTraceAsString(e));
		}
		return false;
	}
	
	
	
	/**
	 * sft文件上传
	 * @param folder 文件夹  如：account账户、activity:活动，多层目录用/隔开，如：user/image用户头像
	 * @param file 上传文件流对应的name值
	 * @param oldFileId 原文件id
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Map<String, Object> singleUpload(HttpServletRequest request) {
		String folder = request.getParameter("folder"); // 文件夹路径
		if(StringUtils.isEmpty(folder)){
			return ResponseCode.buildReturnMap(ResponseCode.FILE_FOLDER_NOT_NULL, null);
		}
		String oldFileId = request.getParameter("oldFileId"); //

		SysConfigDto sysConfig = sysConfigFeignClient.getSysConfig();
		String uploadFilePath = sysConfig.getUploadFilePath();
		// 处理文件夹和文件名称，所有的文件都存储在upload目录下
		Accessory accessory = null;
		String fileName = ""; 
		folder = uploadFilePath + "/" + folder;
		if (StringUtils.isNotEmpty(oldFileId)) {
			accessory = accessoryService.selectByPrimaryKey(CommUtil.null2Long(oldFileId));
			folder = (accessory != null) ? accessory.getPath() : folder;
			fileName = (accessory != null) ? accessory.getName() : "";
		}

		try {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multiRequest.getFile("file"); // 上传文件流对应的name值
			if (file == null) {
				return ResponseCode.buildReturnMap(ResponseCode.FILE_INPUT_NULL, null);
			}
			if (file.getSize() > 10 * 1024 * 1024) { // 上传文件不能超过10MB
				return ResponseCode.buildReturnMap(ResponseCode.FILE_MORE_SIZE, null);
			}
			// 文件后缀
			String extend = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
					.toLowerCase();
			//验证图片格式
			boolean imgflag = CommUtil.isImg(extend.toLowerCase());
			if (!imgflag) {
				return ResponseCode.buildReturnMap(ResponseCode.PARAMETER_ERROR, null);
			}
			
			if (StringUtils.isEmpty(fileName)) { // 文件名字
				fileName = UUID.randomUUID().toString() + "." + extend;
			}
			
			// 图片长和宽,此代码要放sftp之前，ftp上传完成后会关闭流
			int width = 0, height = 0;
			try {
				BufferedImage bis = ImageIO.read(file.getInputStream());
				width = bis.getWidth();
				height = bis.getHeight();
				bis.flush();
			} catch (Exception e) {
			}
			
			// FTP服务器配置
			List<FTPServer> ftpServers = ftpServerService.queryPageList(new HashMap<String, Object>());
			if (ftpServers == null || ftpServers.size() < 1) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_CONFIG_NULL, null);
			}
			
			// 上传文件到SFTP
			FTPServer ftpServer = ftpServers.get(0);
			ChannelSftp sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), 
					ftpServer.getFtp_username(), EncryptUtil.decrypt(ftpServer.getFtp_password()));
			if (sftp == null) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_CONNECT_FAILURE, null);
			}
			Boolean flag = SFtpUtil.upload(sftp, file.getInputStream(), folder, fileName);
			if (!flag) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_UPLOAD_FILE_FAILURE, null);
			}
			// 记录到数据库
			if(accessory == null){
				accessory = new Accessory();
			}
			accessory.setName(fileName);
			accessory.setExt(extend);
			accessory.setSize(BigDecimal.valueOf(file.getSize()));
			accessory.setPath(folder);
			accessory.setWidth(CommUtil.null2Int(width));
			accessory.setHeight(CommUtil.null2Int(height));
			accessory.setUser_id(SecurityUserHolder.getCurrentUserId(request));
			if(accessory.getId() != null){
				accessoryService.update(accessory);
			}else{
				accessory.setAddTime(new Date());
				accessory.setDeleteStatus(0);
				accessoryService.save(accessory);
			}
				InputStream smallInput = null;
				File smallFile = null;
				try {
					String smallFileName = fileName + "_small." + extend;
					String target_path = fileUploadPath + folder;
					File target_path_File = new File(target_path);
					if (!target_path_File.exists()) {
						target_path_File.mkdirs();
					}
					String target = fileUploadPath + folder + "/" + smallFileName;
					CommUtil.createSmall(target, file.getInputStream(), sysConfig.getSmallWidth(),
							sysConfig.getSmallHeight());
					sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), ftpServer.getFtp_username(),
							EncryptUtil.decrypt(ftpServer.getFtp_password()));
					smallFile = new File(target);
					smallInput = new FileInputStream(new File(target));
					flag = SFtpUtil.upload(sftp, smallInput, folder, smallFileName);
				} catch (Exception e) {
					log.error("保存信息有误");
				} finally {
					if (smallInput != null) {
						smallInput.close();
					}
					if (smallFile != null && smallFile.isFile()) {
						smallFile.delete();
					}
				}
			InputStream middleInput = null;
			File middleFile = null;
			try {
				String middleFileName = fileName + "_middle." + extend;
				String target_path = fileUploadPath + folder;
				File target_path_File = new File(target_path);
				if (!target_path_File.exists()) {
					target_path_File.mkdirs();
				}
				String target = fileUploadPath + folder + "/" + middleFileName;
				CommUtil.createSmall(target, file.getInputStream(), sysConfig.getMiddleWidth(),
						sysConfig.getMiddleHeight());
				sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), ftpServer.getFtp_username(),
						EncryptUtil.decrypt(ftpServer.getFtp_password()));
				middleFile = new File(target);
				middleInput = new FileInputStream(new File(target));
				flag = SFtpUtil.upload(sftp, middleInput, folder, middleFileName);
			} catch (Exception e) {
				log.error("保存信息有误");
			} finally {
				if (middleInput != null) {
					middleInput.close();
				}
				if (middleFile != null && middleFile.isFile()) {
					middleFile.delete();
				}
			}
			HashMap<String, Object> result = new HashMap<String, Object>();
			result.put("accessory", accessory);
			
			return ResponseCode.buildReturnMap(ResponseCode.SUCCESS, result);
			
		} catch (Exception e) {
			return ResponseCode.buildReturnMap(ResponseCode.FTP_UPLOAD_FILE_FAILURE, null);
		}
		
	}
	/**
	 * sft文件上传
	 * @param folder 文件夹  如：account账户、activity:活动，多层目录用/隔开，如：user/image用户头像
	 * @param file 上传文件流对应的name值
	 * @param oldFileId 原文件id
	 * @return
	 */
	@RequestMapping(value = "/apiPc/upload", method = RequestMethod.POST)
	public Map<String, Object> adminUpload(HttpServletRequest request) {
		String folder = request.getParameter("folder"); // 文件夹路径
		
		String oldFileId = request.getParameter("oldFileId"); //
		SysConfigDto sysConfig = sysConfigFeignClient.getSysConfig();
		String uploadFilePath = sysConfig.getUploadFilePath();
		
		// 处理文件夹和文件名称，所有的文件都存储在upload目录下
		Accessory accessory = null;
		String fileName = ""; 
		if (StringUtils.isEmpty(folder)) {
			folder = "default";
		}
		folder = uploadFilePath + "/" + folder;
		if (StringUtils.isNotEmpty(oldFileId)) {
			accessory = accessoryService.selectByPrimaryKey(CommUtil.null2Long(oldFileId));
			folder = (accessory != null) ? accessory.getPath() : folder;
			fileName = (accessory != null) ? accessory.getName() : "";
		}
		
		try {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multiRequest.getFile("file"); // 上传文件流对应的name值
			if (file == null) {
				return ResponseCode.buildReturnMap(ResponseCode.FILE_INPUT_NULL, null);
			}
			if (file.getSize() > 10 * 1024 * 1024) { // 上传文件不能超过10MB
				return ResponseCode.buildReturnMap(ResponseCode.FILE_MORE_SIZE, null);
			}
			
			// 文件后缀
			String extend = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
					.toLowerCase();
			//验证图片格式
			boolean imgflag = CommUtil.isImg(extend.toLowerCase());
			if (!imgflag) {
				return ResponseCode.buildReturnMap(ResponseCode.PARAMETER_ERROR, null);
			}
			if (StringUtils.isEmpty(fileName)) { // 文件名字
				fileName = UUID.randomUUID().toString() + "." + extend;
			}
			
			// 图片长和宽,此代码要放sftp之前，ftp上传完成后会关闭流
			int width = 0, height = 0;
			try {
				BufferedImage bis = ImageIO.read(file.getInputStream());
				width = bis.getWidth();
				height = bis.getHeight();
				bis.flush();
			} catch (Exception e) {
			}
			
			// FTP服务器配置
			List<FTPServer> ftpServers = ftpServerService.queryPageList(new HashMap<String, Object>());
			if (ftpServers == null || ftpServers.size() < 1) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_CONFIG_NULL, null);
			}
			
			// 上传文件到SFTP
			FTPServer ftpServer = ftpServers.get(0);
			ChannelSftp sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), 
					ftpServer.getFtp_username(), EncryptUtil.decrypt(ftpServer.getFtp_password()));
			if (sftp == null) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_CONNECT_FAILURE, null);
			}
			Boolean flag = SFtpUtil.upload(sftp, file.getInputStream(), folder, fileName);
			if (!flag) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_UPLOAD_FILE_FAILURE, null);
			}
			
			// 记录到数据库
			if(accessory == null){
				accessory = new Accessory();
			}
			accessory.setName(fileName);
			accessory.setExt(extend);
			accessory.setSize(BigDecimal.valueOf(file.getSize()));
			accessory.setPath(folder);
			accessory.setWidth(CommUtil.null2Int(width));
			accessory.setHeight(CommUtil.null2Int(height));
			accessory.setUser_id(SecurityUserHolder.getCurrentUserId(request));
			if(accessory.getId() != null){
				accessoryService.update(accessory);
			}else{
				accessory.setAddTime(new Date());
				accessory.setDeleteStatus(0);
				accessoryService.save(accessory);
			}
			
			//--start
			InputStream smallInput = null;
			File smallFile = null;
			try {
				String smallFileName = fileName + "_small." + extend;
				String target_path = fileUploadPath + folder;
				File target_path_File = new File(target_path);
				if (!target_path_File.exists()) {
					target_path_File.mkdirs();
				}
				String target = fileUploadPath + folder + "/" + smallFileName;
				CommUtil.createSmall(target, file.getInputStream(), sysConfig.getSmallWidth(),
						sysConfig.getSmallHeight());
				sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), ftpServer.getFtp_username(),
						EncryptUtil.decrypt(ftpServer.getFtp_password()));
				smallFile = new File(target);
				smallInput = new FileInputStream(new File(target));
				flag = SFtpUtil.upload(sftp, smallInput, folder, smallFileName);
			} catch (Exception e) {
				log.error("保存信息有误");
			} finally {
				if (smallInput != null) {
					smallInput.close();
				}
				if (smallFile != null && smallFile.isFile()) {
					smallFile.delete();
				}
			}
		InputStream middleInput = null;
		File middleFile = null;
		try {
			String middleFileName = fileName + "_middle." + extend;
			String target_path = fileUploadPath + folder;
			File target_path_File = new File(target_path);
			if (!target_path_File.exists()) {
				target_path_File.mkdirs();
			}
			String target = fileUploadPath + folder + "/" + middleFileName;
			CommUtil.createSmall(target, file.getInputStream(), sysConfig.getMiddleWidth(),
					sysConfig.getMiddleHeight());
			sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), ftpServer.getFtp_username(),
					EncryptUtil.decrypt(ftpServer.getFtp_password()));
			middleFile = new File(target);
			middleInput = new FileInputStream(new File(target));
			flag = SFtpUtil.upload(sftp, middleInput, folder, middleFileName);
		} catch (Exception e) {
			log.error("保存信息有误");
		} finally {
			if (middleInput != null) {
				middleInput.close();
			}
			if (middleFile != null && middleFile.isFile()) {
				middleFile.delete();
			}
		}
		//--end
			return ResponseCode.buildReturnMap(ResponseCode.SUCCESS, accessory);
			
		} catch (Exception e) {
			return ResponseCode.buildReturnMap(ResponseCode.FTP_UPLOAD_FILE_FAILURE, null);
		}
		
	}
	
	
	/**
	 * sft网络文件上传
	 * @param folder 文件夹  如：account账户、activity:活动，多层目录用/隔开，如：user/image用户头像
	 * @param file_url 网络流地址
	 * @param oldFileId 原文件id
	 * @param extend 文件后缀
	 * @param user_id 用户id
	 * @return
	 */
	@RequestMapping(value = "/apiForFeign/upload", method = RequestMethod.POST)
	public Accessory upload(@RequestParam("folder") String folder, @RequestParam("oldFileId") String oldFileId,
			@RequestParam("extend") String extend, @RequestParam("user_id") Long user_id,
			@RequestParam("file_url") String file_url) {
		if(StringUtils.isEmpty(folder)){
			log.info("sft网络文件上传,路径为空！");
			return null;
		}
		
		// 处理文件夹和文件名称，所有的文件都存储在upload目录下
		Accessory accessory = null;
		String fileName = ""; 
		if (StringUtils.isNotEmpty(oldFileId)) {
			accessory = accessoryService.selectByPrimaryKey(CommUtil.null2Long(oldFileId));
			folder = (accessory != null) ? accessory.getPath() : folder;
			fileName = (accessory != null) ? accessory.getName() : "";
		}
		//验证图片格式
		boolean imgflag = CommUtil.isImg(extend.toLowerCase());
		if (!imgflag) {
			log.info("FTP上传失败！,参数不合法");
			return null;
		}
		if (StringUtils.isEmpty(fileName)) { // 文件名字
			fileName = UUID.randomUUID().toString() + "." + extend;
		}
		
		URL url = null;
        HttpsURLConnection conn = null;
        HttpURLConnection conn1 = null;
		InputStream in = null;
		OutputStream os = null;
		String filePath = ""; // 上传文件本地目录全路径+文件名
		try {
			url = new URL(file_url);
			if(file_url.startsWith("http://")){
				conn1 = (HttpURLConnection)url.openConnection();
				in = conn1.getInputStream();
			}else{
				conn = (HttpsURLConnection) url.openConnection();
				in = conn.getInputStream();
			}
			

			// FTP文件上传路径
			String uploadFilePath = sysConfigFeignClient.getSysConfig().getUploadFilePath();
			folder = uploadFilePath + "/" + folder;
			
			// 本地临时文件夹上传目录
			String path = fileUploadPath+folder;
			File fileDir = new File(path);
			if(!fileDir.exists()){
				fileDir.mkdirs();
			}
			// 设置数据缓冲
	        byte[] bs = new byte[1024 * 2];
	        // 读取到的数据长度
	        int len = 0;
	        // 输出的文件流保存图片至本地
	        filePath = fileDir+"/"+fileName;
	        os = new FileOutputStream(filePath);
	        while ((len = in.read(bs)) != -1) {
	            os.write(bs, 0, len);
	        }
	        os.flush();
	        in = new FileInputStream(new File(filePath));
		}catch (Exception e) {
			log.error("sft网络文件上传,存储本地文件失败:"+Exceptions.getStackTraceAsString(e));
			return null;
		} finally {
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					log.error("关闭流失败："+Exceptions.getStackTraceAsString(e));
				}
			}
			if(conn != null){
				conn.disconnect();
			}
			if(conn1 != null){
				conn1.disconnect();
			}
			if(os != null){
				try {
					os.close();
				} catch (IOException e) {
					log.error("关闭流失败："+Exceptions.getStackTraceAsString(e));
				}
			}
		}
        
		InputStream inStream = null;
		try {
			inStream = new FileInputStream(new File(filePath));
			Integer size = inStream.available();
			/*if (size > 10 * 1024 * 1024) { // 上传文件不能超过10MB
				log.info("sft网络文件上传,大于10MB");
				return null;
			}*/
			
			// 图片长和宽,此代码要放sftp之前，ftp上传完成后会关闭流
			int width = 0, height = 0;
			try {
				BufferedImage bis = ImageIO.read(inStream);
				width = bis.getWidth();
				height = bis.getHeight();
				bis.flush();
			} catch (Exception e) {
			}
			
			// FTP服务器配置
			List<FTPServer> ftpServers = ftpServerService.queryPageList(new HashMap<String, Object>());
			if (ftpServers == null || ftpServers.size() < 1) {
				log.info("sft网络文件上传,FTP服务器未配置");
				return null;
			}
			
			// 上传文件到SFTP
			FTPServer ftpServer = ftpServers.get(0);
			ChannelSftp sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), 
					ftpServer.getFtp_username(), EncryptUtil.decrypt(ftpServer.getFtp_password()));
			if (sftp == null) {
				log.info("sft网络文件上传,FTP连接失败！");
				return null;
			}
			Boolean flag = SFtpUtil.upload(sftp, folder, filePath);
			if (!flag) {
				log.info("sft网络文件上传,FTP上传失败！");
				return null;
			}
			
			// 记录到数据库
			if(accessory == null){
				accessory = new Accessory();
			}
			accessory.setName(fileName);
			accessory.setExt(extend);
			accessory.setSize(new BigDecimal(size));
			accessory.setPath(folder);
			accessory.setWidth(CommUtil.null2Int(width));
			accessory.setHeight(CommUtil.null2Int(height));
			accessory.setUser_id(user_id);
			if(accessory.getId() != null){
				accessoryService.update(accessory);
			}else{
				accessory.setAddTime(new Date());
				accessory.setDeleteStatus(0);
				accessoryService.save(accessory);
			}
			return accessory;
		} catch (Exception e) {
			log.info("sft网络文件上传异常！");
			return null;
		}finally {
			if(inStream != null){
				try {
					inStream.close();
				} catch (IOException e) {
					log.error("关闭流失败："+Exceptions.getStackTraceAsString(e));
				}
			}
			if(StringUtils.isNotEmpty(filePath)){
				File file = new File(filePath);
				if(file.exists()){
					file.delete();
				}
			}
		}
		
	}


	/**
	 * sft网络文件上传
	 * @param folder 文件夹  如：account账户、activity:活动，多层目录用/隔开，如：user/image用户头像
	 * @param file_url 网络流地址
	 * @param oldFileId 原文件id
	 * @param extend 文件后缀
	 * @param user_id 用户id
	 * @return
	 */
	@RequestMapping(value = "/apiForFeign/uploadWithBase64String", method = RequestMethod.POST)
	public Accessory uploadWithBase64String(@RequestBody Map<String, Object> params)  {
		String folder = CommUtil.null2String(params.get("folder"));
		String oldFileId=  CommUtil.null2String(params.get("oldFileId"));
		String extend = CommUtil.null2String(params.get("extend") );
		Long user_id = CommUtil.null2Long(params.get("user_id") );
		String base64_string = CommUtil.null2String(params.get("base64_string"));

		if(StringUtils.isBlank(base64_string)){
			log.info("sft文件上传,文件错误！");
			return null;
		}
		base64_string = base64_string.replaceAll("data:image/jpeg;base64,","");

		if(StringUtils.isEmpty(folder)){
			log.info("sft文件上传,路径为空！");
			return null;
		}

		// 处理文件夹和文件名称，所有的文件都存储在upload目录下
		Accessory accessory = null;
		String fileName = "";
		if (StringUtils.isNotEmpty(oldFileId)) {
			accessory = accessoryService.selectByPrimaryKey(CommUtil.null2Long(oldFileId));
			folder = (accessory != null) ? accessory.getPath() : folder;
			fileName = (accessory != null) ? accessory.getName() : "";
		}
		//验证图片格式
		boolean imgflag = CommUtil.isImg(extend.toLowerCase());
		if (!imgflag) {
			log.info("FTP上传失败！,参数不合法");
			return null;
		}
		if (StringUtils.isEmpty(fileName)) { // 文件名字
			fileName = UUID.randomUUID().toString() + "." + extend;
		}

		InputStream in = null;
		OutputStream os = null;

		String filePath = ""; // 上传文件本地目录全路径+文件名
		try {
			// FTP文件上传路径
			String uploadFilePath = sysConfigFeignClient.getSysConfig().getUploadFilePath();
			folder = uploadFilePath + "/" + folder;

			// 本地临时文件夹上传目录
			String path = fileUploadPath + folder;
			File fileDir = new File(path);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}

			BASE64Decoder decoder = new BASE64Decoder();
			byte[] bytes1 = decoder.decodeBuffer(base64_string.replaceAll(" ", ""));
			in = new ByteArrayInputStream(bytes1);

			// 设置数据缓冲
			byte[] bs = new byte[1024 * 2];
			// 读取到的数据长度
			int len = 0;
			// 输出的文件流保存图片至本地
			filePath = fileDir + "/" + fileName;
			os = new FileOutputStream(filePath);
			while ((len = in.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			os.flush();

		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					log.error("关闭流失败："+Exceptions.getStackTraceAsString(e));
				}
			}
		}


		InputStream inStream = null;
		try {
			inStream = new FileInputStream(new File(filePath));
			Integer size = inStream.available();
			// FTP服务器配置
			List<FTPServer> ftpServers = ftpServerService.queryPageList(new HashMap<String, Object>());
			if (ftpServers == null || ftpServers.size() < 1) {
				log.error("sft网络文件上传,FTP服务器未配置");
				return accessory;
			}
			// 上传文件到SFTP
			FTPServer ftpServer = ftpServers.get(0);
			ChannelSftp sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(),
					ftpServer.getFtp_username(), EncryptUtil.decrypt(ftpServer.getFtp_password()));
			if (sftp == null) {
				return accessory;
			}

			//Boolean flag = SFtpUtil.upload(sftp, inStream, folder, fileName);
			Boolean flag = SFtpUtil.upload(sftp, folder, filePath);
			if (!flag) {
				return accessory;
			}

			// 记录到数据库
			if (accessory == null) {
				accessory = new Accessory();
			}


			accessory.setName(fileName);
			accessory.setExt(extend);
			accessory.setSize(new BigDecimal(size));
			accessory.setPath(folder);
			accessory.setUser_id(user_id);
			if (accessory.getId() != null) {
				accessoryService.update(accessory);
			} else {
				accessory.setAddTime(new Date());
				accessory.setDeleteStatus(0);
				accessoryService.save(accessory);
			}
			return accessory;
		} catch (IOException e) {
			e.printStackTrace();
			log.error("sft网络文件上传异常！");
			return null;
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					log.error("关闭流失败：" + Exceptions.getStackTraceAsString(e));
				}
			}
		}
	}

	/**
	 * sft文件上传视频
	 * @param folder 文件夹  如：account账户、activity:活动，多层目录用/隔开，如：user/image用户头像
	 * @param file 上传文件流对应的name值
	 * @param oldFileId 原文件id
	 * @return
	 */
	@RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
	public Map<String, Object> uploadVideo(HttpServletRequest request) {
		 
		String folder = request.getParameter("folder"); // 文件夹路径
		if(StringUtils.isEmpty(folder)){
			return ResponseCode.buildReturnMap(ResponseCode.FILE_FOLDER_NOT_NULL, null);
		}
		String oldFileId = request.getParameter("oldFileId"); //

		String uploadFilePath = sysConfigFeignClient.getSysConfig().getUploadFilePath();
		
		// 处理文件夹和文件名称，所有的文件都存储在upload目录下
		Accessory accessory = null;
		String fileName = ""; 
		folder = uploadFilePath + "/" + folder + "/" +DateUtils.getDate("yyyyMM"); // 拼接年月
		if (StringUtils.isNotEmpty(oldFileId)) {
			accessory = accessoryService.selectByPrimaryKey(CommUtil.null2Long(oldFileId));
			folder = (accessory != null) ? accessory.getPath() : folder;
			fileName = (accessory != null) ? accessory.getName() : "";
		}

		String videoPath = ""; // 上传文件本地目录全路径+文件名
		String imagePath = ""; // 第一帧图片路全路径
		InputStream imageIn = null;
		try {
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			MultipartFile file = multiRequest.getFile("file"); // 上传文件流对应的name值
			if (file == null) {
				return ResponseCode.buildReturnMap(ResponseCode.FILE_INPUT_NULL, null);
			}
			if (file.getSize() > 50 * 1024 * 1024) { // 上传文件不能超过50MB
				return ResponseCode.buildReturnMap(ResponseCode.FILE_MORE_SIZE, null);
			}
			// FTP服务器配置
			List<FTPServer> ftpServers = ftpServerService.queryPageList(new HashMap<String, Object>());
			if (ftpServers == null || ftpServers.size() < 1) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_CONFIG_NULL, null);
			}
			
			// 上传文件到SFTP
			FTPServer ftpServer = ftpServers.get(0);
						
			// 文件后缀
			String extend = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
					.toLowerCase();
			if (StringUtils.isEmpty(fileName)) { // 文件名字
				fileName = UUID.randomUUID().toString() + "." + extend;
			}
			
			// 本地临时文件夹上传目录
			String path = fileUploadPath+folder;
			File fileDir = new File(path);
			if(!fileDir.exists()){
				fileDir.mkdirs();
			}
			// 设置数据缓冲
	        byte[] bs = new byte[1024 * 2];
	        // 读取到的数据长度
	        int len = 0;
	        // 输出的文件流保存视频至本地
	        videoPath = fileDir+"/"+fileName;
	        InputStream in = null;
			OutputStream os = null;
			try{
		        os = new FileOutputStream(videoPath);
		        in = file.getInputStream();
		        while ((len = in.read(bs)) != -1) {
		            os.write(bs, 0, len);
		        }
		        os.flush();
			}catch (Exception e) {
				return ResponseCode.buildCodeMap("10009", "上传文件到本地失败，请联系管理员！", null);
			}finally {
				if(os != null){
					try {
						os.close();
					} catch (IOException e) {
						log.error("关闭流失败："+Exceptions.getStackTraceAsString(e));
					}
				}
				if(in != null){
					try {
						in.close();
					} catch (IOException e) {
						log.error("关闭流失败："+Exceptions.getStackTraceAsString(e));
					}
				}
			}
			
	        // 生成第一帧图片
	        String videoImageName = UUID.randomUUID().toString() + ".jpg";
	        try {
				VideoFrameUtils.randomGrabberFFmpegImage(videoPath, path, videoImageName);
			} catch (Exception e1) {
				return ResponseCode.buildCodeMap("10010", "视频生成第一帧失败，请联系管理员！", null);
			}
	        imagePath = fileDir+"/"+videoImageName;
	        
	        File imagePathFile = new File(imagePath);
	        imageIn = new FileInputStream(imagePathFile);
	    	// 图片长和宽
 			int width = 0, height = 0;
 			try {
				BufferedImage bis = ImageIO.read(in);
				width = bis.getWidth();
				height = bis.getHeight();
				bis.flush();
			} catch (Exception e) {
			}
 			// 上传第一帧图片到Ftp
 			ChannelSftp sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), 
					ftpServer.getFtp_username(), EncryptUtil.decrypt(ftpServer.getFtp_password()));
			if (sftp == null) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_CONNECT_FAILURE, null);
			}
			Boolean flag = SFtpUtil.upload(sftp, imageIn, folder, videoImageName);
			if (!flag) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_UPLOAD_FILE_FAILURE, null);
			}
			
			Accessory imageAcc = new Accessory();
			imageAcc.setName(videoImageName);
			imageAcc.setExt("jpg");
			imageAcc.setSize(BigDecimal.valueOf(imagePathFile.length()));
			imageAcc.setPath(folder);
			imageAcc.setWidth(CommUtil.null2Int(width));
			imageAcc.setHeight(CommUtil.null2Int(height));
			imageAcc.setUser_id(SecurityUserHolder.getCurrentUserId(request));
			imageAcc.setAddTime(new Date());
			imageAcc.setDeleteStatus(0);
			accessoryService.save(imageAcc);
			
			
			// 上传视频到FTP
			try {
				BufferedImage bis = ImageIO.read(file.getInputStream());
				width = bis.getWidth();
				height = bis.getHeight();
				bis.flush();
			} catch (Exception e) {
			}
			sftp = SFtpUtil.connect(ftpServer.getFtp_ip(), ftpServer.getFtp_port(), 
					ftpServer.getFtp_username(), EncryptUtil.decrypt(ftpServer.getFtp_password()));
			if (sftp == null) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_CONNECT_FAILURE, null);
			}
			flag = SFtpUtil.upload(sftp, file.getInputStream(), folder, fileName);
			if (!flag) {
				return ResponseCode.buildReturnMap(ResponseCode.FTP_UPLOAD_FILE_FAILURE, null);
			}
			
			// 记录到数据库
			if(accessory == null){
				accessory = new Accessory();
			}
			accessory.setName(fileName);
			accessory.setExt(extend);
			accessory.setSize(BigDecimal.valueOf(file.getSize()));
			accessory.setPath(folder);
			accessory.setWidth(CommUtil.null2Int(width));
			accessory.setHeight(CommUtil.null2Int(height));
			accessory.setUser_id(SecurityUserHolder.getCurrentUserId(request));
			if(accessory.getId() != null){
				accessoryService.update(accessory);
			}else{
				accessory.setAddTime(new Date());
				accessory.setDeleteStatus(0);
				accessoryService.save(accessory);
			}
			HashMap<String, Object> result = new HashMap<String, Object>();
			result.put("video", accessory);
			result.put("image", imageAcc);
			
			return ResponseCode.buildReturnMap(ResponseCode.SUCCESS, result);
			
		} catch (Exception e) {
			return ResponseCode.buildReturnMap(ResponseCode.FTP_UPLOAD_FILE_FAILURE, null);
		}finally {
			if(imageIn != null){
				try {
					imageIn.close();
				} catch (IOException e) {
				}
			}
			if(StringUtils.isNotEmpty(videoPath)){
				File file = new File(videoPath);
				if(file.exists()){
					file.delete();
				}
			}
			if(StringUtils.isNotEmpty(imagePath)){
				File file = new File(imagePath);
				if(file.exists()){
					file.delete();
				}
			}
		}
		
	}
}
